<template>
  <el-upload
    ref="upload"
    action="#"
    accept=".xlsx, .xls"
    :limit="1"
    :on-exceed="handleExceed"
    :on-change="handleChange"
    :auto-upload="false"
    :show-file-list="false"
  >
    <template #trigger>
      <el-button type="primary" class="import-btn">导入</el-button>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage, genFileId, UploadFile, UploadFiles } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { read, utils } from "xlsx";

import { formatExcelTime } from "@/utils/formatExcelTime.ts";

import { importPartyMember } from "@/api/member/index.ts";
import { useStore } from "vuex";

const props = defineProps(["isCover"]);
const emits = defineEmits(["upload"]);

const upload = ref<UploadInstance>();

const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

const map: IObj = {
  '姓名': "name",
  '性别': "sex",
  '学号': "studentID",
  '学院': "college",
  '加入时间': "joinTime",
  '联系电话': "phone",
};

const handleChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  // 通过FileReader对象读取文件
  const fileReader = new FileReader();
  fileReader.onload = (event: ProgressEvent) => {
    try {
      const { result } = event.target as FileReader;
      // 以二进制流方式读取得到整份excel表格对象
      const workbook = read(result, { type: "binary" });

      let data: IObj[] = []; // 存储获取到的数据

      for (const sheet in workbook.Sheets) {
        // 利用 sheet_to_json 方法将 excel 转成 json 数据

        if (sheet !== "填写须知") {
          data = data.concat(utils.sheet_to_json(workbook.Sheets[sheet]));
        }
      }

      getPostData(data);
    } catch (e) {
      ElMessage({
        type: "error",
        message: "文件类型不正确",
      });
      return;
    }
  };
  // 以二进制方式打开文件
  fileReader.readAsBinaryString(uploadFiles[0].raw as Blob);
};

const store = useStore();

const getPostData = (data: IObj[]) => {
  const postData: IObj[] = [];

  for (const row of data) {
    const obj: IObj = {};

    for (const item in row) {
      if (Object.keys(map).includes(item)) {
        if (item.includes("时间")) {
          obj[map[item]] = formatExcelTime(row[item]);
        } else if (item === "联系电话") {
          obj[map[item]] = row[item].toString();
        } else {
          obj[map[item]] = row[item];
        }
      } else if (item === "所在社团") {
        const organizationMap = store.getters.organizationMap;

        const organizations = row[item].split("、");

        for (const organization of organizations) {
          for (const id in organizationMap) {
            if (organizationMap[id] === organization) {
              if (Array.isArray(obj.organizations)) {
                obj.organizations.push(id);
              } else {
                obj.organizations = [id];
              }
            }
          }

          if (!Array.isArray(obj.organizations)) {
            ElMessage({
              type: "error",
              message: `请先新增对应社团`,
            });
            return;
          }
        }
      }
    }

    postData.push(obj);
  }

  importPartyMember(props.isCover, postData).then((res: IObj) => {
    if (res.data.code == 200) {
      emits("upload");
    }
  });
};
</script>

<style scoped>
.import-btn {
  width: 100px;
  margin-top: 20px;
}
</style>
